//
//  UniversalLinksCenter.swift
//  App_Common
//
//  Created by 蒋晨成 on 2021/12/24.
//

import Foundation
import Standard
import URLRoute

public enum UniversalLinksCenter {}
extension UniversalLinksCenter: TypeName {}

private extension UniversalLinksCenter {
    static let matcher = URLMatcher()
    static let universalLinksFactories: [URLPattern: URLPattern] = {
        [
            "https://jccapril.github.io/e/b/<string:title>": "example/button/update/<title>",
        ]
    }()
}

public extension UniversalLinksCenter {
    static func handle(url: String) -> URLPattern? {
        let urlPatterns = Array(universalLinksFactories.keys)
        guard let match = matcher.match(url, from: urlPatterns) else { return nil }
        guard let pattern = universalLinksFactories[match.pattern] else { return nil }
        return generateURL(from: pattern, params: match.values)
    }
}

extension UniversalLinksCenter {
    static func generateURL(from url: String, params: [String: Any]) -> String {
        let values = url.string.components(separatedBy: "/").map { string -> String in
            let key: String = string.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: ">", with: "")
            switch (string.hasPrefix("<") && string.hasSuffix(">"), params.keys.contains(key)) {
            case (true, true):
                switch params[key] {
                case let int as Int: return String(int)
                case let int64 as Int64: return String(int64)
                case let uint as UInt: return String(uint)
                case let uint64 as UInt64: return String(uint64)
                case let double as Double: return String(double)
                case let float as Float: return String(float)
                case let str as String: return str
                default: return string
                }
            default: return string
            }
        }
        return values.joined(separator: "/")
    }
}
